/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sigmatrix.h5.dao.DisRebateScanCodeDao;
import com.sigmatrix.h5.entity.DisDealer;
import com.sigmatrix.h5.entity.DisRebateScanCode;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.service.DisDealerService;
import com.sigmatrix.h5.service.DisRebateScanCodeService;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Constants;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.web.args.DealerInventoryPageParam;
import com.sigmatrix.h5.web.mode.DealerInventory;
import com.sigmatrix.h5.web.mode.DealerInventoryData;
import com.sigmatrix.h5.web.mode.DealerInventoryDayCount;
import com.sigmatrix.sc.jdbc.common.lang.Page;
import com.sigmatrix.sc.jdbc.common.service.ServiceImpl;

/**
 *@ClassName: DisRebateScanCodeServiceImpl
 *@Description: 
 *@author MH
 *@date 2017年8月14日 下午8:03:21
 */
@Service
public class DisRebateScanCodeServiceImpl extends ServiceImpl<DisRebateScanCode,Integer> implements DisRebateScanCodeService{
	@Autowired
	private DisRebateScanCodeDao disRebateScanCodeDao;
	
	@Autowired
	private DisDealerService disDealerService;
	
	@Override
	@Deprecated
	public Integer selectCountByDealerAcctsIdAndActivityId(String acct, Integer activityId){
		return disRebateScanCodeDao.selectCountByDealerAcctsIdAndActivityId(acct, activityId);
	}
	@Override
	public Integer selectCountByDealerIdAndActivityId(Integer dealerId, Integer activityId){
		return disRebateScanCodeDao.selectCountByDealerIdAndActivityId(dealerId, activityId);
	}
	@Override
	public DisRebateScanCode findLastScanDealer(String qrCode) {
		List<DisRebateScanCode> list = findScanHistory(qrCode);
		return CommonUtils.isEmpty(list)?null:list.get(0);
	}
	
	@Override
	public List<DisRebateScanCode> findScanHistory(String qrCode){
		DisRebateScanCode code = new DisRebateScanCode();
		code.setQrCode(qrCode);
		code.setStatus(Constants.STATUS_ENABLE);
		Map<String,String> order = new HashMap<String,String>();
		order.put("scanTime", "desc");
		return select(code, order);
	}
	
	
	@Override
	public List<DisDealer> determineRebateDealers(List<DisRebateScanCode> scanHistory,Map<Integer, String> dealers){
		Integer lastScanDealerId = scanHistory.get(0).getDealerId();
		Map<Integer,DisDealer> map = new HashMap<Integer, DisDealer>();
		boolean feeling = true;
		List<DisDealer> children = disDealerService.findChildren(lastScanDealerId);
		List<DisDealer> parent = disDealerService.findParents(lastScanDealerId);
		children.addAll(parent);
		Collections.sort(children, (a,b) -> a.getLevel() - b.getLevel());
		for (DisDealer dealer : children) {
			if(!map.containsKey(dealer.getId())){
				map.put(dealer.getId(), dealer);
				//如果当前经销商的级别比原来经销商级别小，说明是上级重复扫
				if(dealers.containsKey(dealer.getId())){
					DisDealer lastDealer = disDealerService.findById(lastScanDealerId);
					Short l = dealer.getLevel()==null?1:dealer.getLevel();
					if(CrmAcctType.TERMINAL_SHOP.value.equals(SessionUtils.getAcctType())){
						l ++;
					}
					if( l > (lastDealer.getLevel()==null?1:lastDealer.getLevel())){
						feeling = false;
						break;
					}
				}
			}
		}
		//if(feeling) throw new MessageException("您所属的经销商不是上次扫码的经销商的下级经销商，窜货");
		if(feeling) throw new MessageException("非法操作");
		return map.values().stream().collect(Collectors.toList());
	}
	@Override
	public List<DisRebateScanCode> findScanHistory(String urlDomain, String seqNum) {
		DisRebateScanCode scan = new DisRebateScanCode();
		scan.setUrlDomain(urlDomain);
		scan.setSeqNum(seqNum);
		scan.setStatus(Constants.STATUS_ENABLE);
		return select(scan);
	}
	@Override
	public Page<DealerInventoryData> findInventoryPage(DealerInventoryPageParam vo) {
//		Page<DealerInventoryData> page= disRebateScanCodeDao.findPage(vo);
//		if(CommonUtils.isNotEmpty(page)) {
//			List<DealerInventoryDayCount> listDayErrors = disRebateScanCodeErrorService.findDayCountList(vo);
//			for (DealerInventoryData data : page) {
//				for (DealerInventoryDayCount count : listDayErrors) {
//					if(sameDate(count.getScanTimeDay(),data.getScanTimeDay())) {
//						if(data.getScanId().equals(count.getScanId()) && data.getProductName().equals(count.getProductName())) {
//							data.setErrorNum(count.getCount());
//						}
//					}
//				}
//			}
//		}
		return disRebateScanCodeDao.findPage(vo);
	}
	public DisRebateScanCode findFirstScanOfOpenIdByActivity(String openId, Integer activityId) {
		DisRebateScanCode scan = new DisRebateScanCode();
		scan.setOpenId(openId);
		scan.setRebateActivityId(activityId);
		Map<String,String> order = new HashMap<String, String>();
		order.put("scanTime", "");
		return disRebateScanCodeDao.selectOne(scan,order);
	}
	@Override
	public Integer countByOpenIdInHoure(String openId, Integer activityId, Date firstScanTime, int period) {
		return disRebateScanCodeDao.countByOpenIdInHoure(openId,activityId,firstScanTime,period);
	}
	@Override
	public List<DisRebateScanCode> findByOpenId(String openId) {
		DisRebateScanCode code = new DisRebateScanCode();
		code.setOpenId(openId);
		Map<String,String> order = new HashMap<String,String>();
		order.put("scanTime", "desc");
		return select(code,order);
	}
	@Override
	public List<DisRebateScanCode> findScanHistory2_6(String qrCode, String qrCode2) {
		
		return disRebateScanCodeDao.findScanHistory2_6(qrCode, qrCode2);
	}
	@Override
	public List<DealerInventoryDayCount> findDayCount(DealerInventoryPageParam vo) {
		return disRebateScanCodeDao.findDayCount(vo);
	}
	@Override
	public DealerInventory findDealerInventory(DealerInventoryPageParam vo) {
		Page<DealerInventoryData> page= findInventoryPage(vo);
		DealerInventory dealerInventory = new DealerInventory();
		dealerInventory.setDatas(page);
		dealerInventory.setPriceTotal(disRebateScanCodeDao.findPriceTotal(vo));
//		dealerInventory.setPriceTotal(page.stream().map(DealerInventoryData :: getPrice ).reduce(BigDecimal.ZERO, BigDecimal :: add));
		return dealerInventory;
	}
//	private static boolean sameDate(Date d1, Date d2) {  
//	    LocalDate localDate1 = ZonedDateTime.ofInstant(d1.toInstant(), ZoneId.systemDefault()).toLocalDate();  
//	    LocalDate localDate2 = ZonedDateTime.ofInstant(d2.toInstant(), ZoneId.systemDefault()).toLocalDate();  
//	    return localDate1.isEqual(localDate2);  
//	} 
}
